#include "ItemFactory.h"

//=====PRIVATE
Item_Base* Factory::create(int const & a_type)
{
	switch(a_type)
	{
	case ITEM_EMPTY:				return new Item_Base;
	case ITEM_EQUIPPABLE:			return new Item_Equippable;
	case ITEM_CONSUMABLE:			return new Item_Consumable;
	case ITEM_PROJECTILE:	
		{
			int nextValidIndex = ITEM_NULL;
			for(int i = 0; nextValidIndex == ITEM_NULL && i < projectilePool.size(); ++i)
			{
				if(projectilePool.get(i).itemType == ITEM_NULL)
				{
					nextValidIndex = i;
					projectilePool.get(i).uniqueID = i;	//Multiplayer specific index
				}

			}
			if(nextValidIndex != ITEM_NULL)		
				return &projectilePool.get(nextValidIndex);
			//Expand the pool if we absolutely have to.
			projectilePool.add();
			projectilePool.getLast().uniqueID = projectilePool.size()-1;
			return & projectilePool.getLast();
		}
	}
	return 0;
}
void Factory::uncreate(Item_Base * e, int a_type)
{
	switch(a_type)
	{
	case ITEM_EMPTY:		delete (Item_Base*)e;						break;
	case ITEM_EQUIPPABLE:	delete (Item_Equippable*)e;					break;
	case ITEM_CONSUMABLE:	delete (Item_Consumable*)e;					break;
	case ITEM_PROJECTILE:	
		{
			e->itemType		= ITEM_NULL;
			e->active		= false;
			e->assetIndex	= m_artAssets[alpha];		
		}
		break;
	}
}

void Factory::update(){
	for(int i=0; i < projectilePool.size(); i++)
		if(projectilePool.get(i).itemType != ITEM_NULL)
		{
			Item_Projectile blah = projectilePool.get(i);
			projectilePool.get(i).update();
			if(projectilePool.get(i).range <= 0)
				uncreate(((Item_Base*)(&projectilePool.get(i))),ITEM_PROJECTILE);
		}
}
void Factory::Release()
{
	projectilePool.clear();
}

void Factory::addMultiplayerProjectile(Item_Projectile* p)
{
	int nextValidIndex = ITEM_NULL;
	p->collideEffect = Item_Projectile::SPELL_MULTIPLAYER_DUD;
	for(int i = 0; nextValidIndex == ITEM_NULL && i < projectilePool.size(); ++i)
	{
		if(projectilePool.get(i).itemType == ITEM_NULL)
		{
			nextValidIndex = i;
		}
	}
	if(nextValidIndex == ITEM_NULL)
	{
		projectilePool.add(*p);
		nextValidIndex = projectilePool.size()-1;
	}
	else
		projectilePool.set(nextValidIndex, *p);
	Engine::Ins()->dlHandler.AddObject(&projectilePool.get(nextValidIndex), DRAW_ENTITIES);
}

